package com.bigtotoro.shuiyincamera.video.trim;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.trim.utils.BackgroundExecutor;
import com.bigtotoro.shuiyincamera.video.trim.utils.SingleCallback;
import com.bigtotoro.shuiyincamera.video.trim.utils.SpacesItemDecoration2;
import com.bigtotoro.shuiyincamera.video.trim.utils.UiThreadExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;
import static com.bigtotoro.shuiyincamera.video.trim.VideoTrimmerUtil.VIDEO_FRAMES_WIDTH;

/**
 * Author：J.Chou
 * Date：  2016.08.01 2:23 PM
 * Email： who_know_me@163.com
 * Describe:
 */
public class VideoTrimmerView extends FrameLayout implements IVideoTrimmerView {

    private static final String TAG = VideoTrimmerView.class.getSimpleName();

    private int mMaxWidth = VIDEO_FRAMES_WIDTH;
    private Context mContext;
    private RelativeLayout mLinearVideo;
    private ZVideoView mVideoView;
    private ImageView mPlayView;
    private RecyclerView mVideoThumbRecyclerView;
    private RangeSeekBarView mRangeSeekBarView;
    private LinearLayout mSeekBarLayout;
    private ImageView mRedProgressIcon;
    private TextView mVideoShootTipTv;
    private float mAverageMsPx;//每毫秒所占的px
    private float averagePxMs;//每px所占用的ms毫秒
    private Uri mSourceUri;
    private VideoTrimListener mOnTrimVideoListener;
    private int mDuration = 0;
    private VideoTrimmerAdapter mVideoThumbAdapter;//视频预览图集合
    private boolean isFromRestore = false;
    //new
    private long mLeftProgressPos, mRightProgressPos;
    private long mRedProgressBarPos = 0;
    private long scrollPos = 0;
    private int mScaledTouchSlop;
    private int lastScrollX;
    private boolean isSeeking;
    private boolean isOverScaledTouchSlop;
    private int mThumbsTotalCount;
    private ValueAnimator mRedProgressAnimator;
    private Handler mAnimationHandler = new Handler();

    public Activity activity;
    private String videoPath;

    public void initVideoPath(String path) {
        videoPath = path;
    }

    public VideoTrimmerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoTrimmerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void initActivity(Activity activity) {
        this.activity = activity;
    }

    //监听拖动条的拖动动作
    private final RangeSeekBarView.OnRangeSeekBarChangeListener mOnRangeSeekBarChangeListener = new RangeSeekBarView.OnRangeSeekBarChangeListener() {
        @Override
        public void onRangeSeekBarValuesChanged(RangeSeekBarView bar, long minValue, long maxValue, int action, boolean isMin, RangeSeekBarView.Thumb pressedThumb) {
            Log.d(TAG, "-----minValue----->>>>>>" + minValue);
            Log.d(TAG, "-----maxValue----->>>>>>" + maxValue);
            mLeftProgressPos = minValue + scrollPos;
            mRedProgressBarPos = mLeftProgressPos;
            mRightProgressPos = maxValue + scrollPos;
            Log.d(TAG, "-----mLeftProgressPos----->>>>>>" + mLeftProgressPos);
            Log.d(TAG, "-----mRightProgressPos----->>>>>>" + mRightProgressPos);
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    //红色动画停止
                    Log.i("开始拖动", "开始拖动 ACTION_DOWN =========================== ");
                    pauseRedProgressAnimation(); //清除红色指示条动画
                    isSeeking = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    isSeeking = true;
                    seekTo((int) (pressedThumb == RangeSeekBarView.Thumb.MIN ? mLeftProgressPos : mRightProgressPos));
                    break;
                case MotionEvent.ACTION_UP:
                    isSeeking = false;
                    seekTo((int) mLeftProgressPos);
                    if (isPauseByUser == 0) {
                        playingRedProgressAnimation(); //停止拖动后，开始播放红色指示条动画
                    }

                    Log.i("开始拖动", "开始拖动 ACTION_UP = ===========================");
                    break;
                default:
                    break;
            }

            mRangeSeekBarView.setStartEndTime(mLeftProgressPos, mRightProgressPos);
        }
    };

    //底部recycleview的滚动动作监听
    private final RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            Log.d(TAG, "newState = " + newState);
            Log.i("开始滚动", "开始滚动 newState = " + newState);
            //红色动画停止
//            pauseRedProgressAnimation(); //清除红色指示条动画

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            isSeeking = false;
            int scrollX = calcScrollXDistance();
            //达不到滑动的距离
            if (Math.abs(lastScrollX - scrollX) < mScaledTouchSlop) {
                isOverScaledTouchSlop = false;
                return;
            }
            Log.i("开始滚动", "滚动结束===== scrollX===" + scrollX);
            isOverScaledTouchSlop = true;
            //初始状态,why ? 因为默认的时候有35dp的空白！
            if (scrollX == -VideoTrimmerUtil.RECYCLER_VIEW_PADDING) {
                scrollPos = 0;
            } else {
                isSeeking = true;
                scrollPos = (long) (mAverageMsPx * (VideoTrimmerUtil.RECYCLER_VIEW_PADDING + scrollX));
                Log.i("开始滚动", "onScrolled >>>> scrollPos = " + scrollPos);//scrollPos=11248
                mLeftProgressPos = mRangeSeekBarView.getSelectedMinValue() + scrollPos;//mLeftProgressPos = 21770,mRightProgressPos==31568
                mRightProgressPos = mRangeSeekBarView.getSelectedMaxValue() + scrollPos;//mRedProgressBarPos = 21770
                Log.i("开始滚动", "onScrolled >>>> mRangeSeekBarView.getSelectedMinValue() = " + mRangeSeekBarView.getSelectedMinValue() + ",mRangeSeekBarView.getSelectedMaxValue()==" + mRangeSeekBarView.getSelectedMaxValue());
                Log.i("开始滚动", "onScrolled >>>> mLeftProgressPos = " + mLeftProgressPos + ",mRightProgressPos==" + mRightProgressPos);
                mRedProgressBarPos = mLeftProgressPos;
                Log.i("开始滚动", "onScrolled >>>> mRedProgressBarPos = " + mRedProgressBarPos);
//                if (mVideoView.isPlaying()) {
//                    mVideoView.pause();
//                    setPlayPauseViewIcon(false);
//                }
//                mRedProgressIcon.setVisibility(GONE); //红色指示条停在了左侧
                seekTo(mLeftProgressPos);  //是否清空了播放进度

                mRangeSeekBarView.setStartEndTime(mLeftProgressPos, mRightProgressPos);
                mRangeSeekBarView.invalidate();

//                playVideoOrPause();
                if (isPauseByUser == 0) {
                    playingRedProgressAnimation(); //停止拖动后，开始播放红色指示条动画
                }
            }
            lastScrollX = scrollX;
        }
    };

    private void init(Context context) {
        this.mContext = context;
        LayoutInflater.from(context).inflate(R.layout.video_trimmer_view, this, true);

        mLinearVideo = findViewById(R.id.layout_surface_view);
        mVideoView = findViewById(R.id.video_loader);
        mPlayView = findViewById(R.id.icon_video_play);
        mSeekBarLayout = findViewById(R.id.seekBarLayout); //剪裁拖动条，每次拖动完需要重新加载视频
        mRedProgressIcon = findViewById(R.id.positionIcon); //红色进度线
        mVideoShootTipTv = findViewById(R.id.video_shoot_tip);
        mVideoThumbRecyclerView = findViewById(R.id.video_frames_recyclerView);
        mVideoThumbRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mVideoThumbAdapter = new VideoTrimmerAdapter(mContext);
        mVideoThumbRecyclerView.setAdapter(mVideoThumbAdapter);

        mVideoThumbRecyclerView.addOnScrollListener(mOnScrollListener);
        setOnClickListeners();  //初始化监听
    }

    private void setOnClickListeners() {
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {//准备完成后自动播放视频
                mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
                videoPrepared(mp);
            }
        });
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                videoCompleted();
            }
        });
        mPlayView.setOnClickListener(new OnClickListener() {  //播放按钮动作监听
            @Override
            public void onClick(View v) {
                playVideoOrPause();
            }
        });
    }

    private int videoWidth, videoHeight;

    private void videoPrepared(MediaPlayer mp) {
        ViewGroup.LayoutParams videoViewLayoutParams = mVideoView.getLayoutParams();
        videoWidth = mp.getVideoWidth();
        videoHeight = mp.getVideoHeight();
        float videoProportion = (float) videoWidth / (float) videoHeight; //计算播放器的宽高比
        int screenWidth = mLinearVideo.getWidth();
        int screenHeight = mLinearVideo.getHeight();
        float screenProportion = (float) screenWidth / (float) screenHeight;  //计算videoview父容器的宽高比
        if (videoProportion > screenProportion) {  //
            videoViewLayoutParams.width = screenWidth;
            videoViewLayoutParams.height = (int) ((float) screenWidth / videoProportion);
        } else {
            videoViewLayoutParams.width = (int) (videoProportion * (float) screenHeight);
            videoViewLayoutParams.height = screenHeight;
        }
        mVideoView.setLayoutParams(videoViewLayoutParams);
        mDuration = mVideoView.getDuration();  //视频总时长
        if (!isFromRestore) {
            seekTo((int) mRedProgressBarPos);  //这个red进度播放时等于视频播放进度，拖拽滚动条之后等于left的进度
        } else {
            setRestoreState(false);
            seekTo((int) mRedProgressBarPos);
        }

        initRangeSeekBarView();   //初始化拖动条
        Log.i("计算缩略图", "计算缩略图 mThumbsTotalCount =========================== " + mThumbsTotalCount);
        startShootVideoThumbs(mContext, mSourceUri, mThumbsTotalCount, 0, mDuration);

        //视频初始化后直接播放
        mVideoView.start();
        playingRedProgressAnimation();
        setPlayPauseViewIcon(mVideoView.isPlaying());
    }

    public void setRestoreState(boolean fromRestore) {
        isFromRestore = fromRestore;
    }


    //初始化拖动条
    private void initRangeSeekBarView() {
        if (mRangeSeekBarView != null) return;
        int rangeWidth;  //mRangeSeekBarView的宽度
        mLeftProgressPos = 0;
        if (((VideoTrimmerActivity)activity).getMode()!=null && ((VideoTrimmerActivity)activity).getMode().equals("extract_bg")){
            //如果是分离音频，设置最长剪辑时长为视频长度
            mThumbsTotalCount = VideoTrimmerUtil.MAX_COUNT_RANGE;  //10
            rangeWidth = mMaxWidth;  //SCREEN_WIDTH_FULL - RECYCLER_VIEW_PADDING * 2;屏幕宽度减两侧padding
            mRightProgressPos = mDuration;
        }else {  //如果是普通裁剪，需要判断视频总时长
            if (mDuration <= VideoTrimmerUtil.MAX_SHOOT_DURATION) {   //如果视频总时长小于10秒
                mThumbsTotalCount = VideoTrimmerUtil.MAX_COUNT_RANGE;  //10
                rangeWidth = mMaxWidth;  //SCREEN_WIDTH_FULL - RECYCLER_VIEW_PADDING * 2;屏幕宽度减两侧padding
                mRightProgressPos = mDuration;
            } else {     //如果视频总时长大于10秒               //15秒的视频为例， 15000/10000*10 = 15
                mThumbsTotalCount = (int) (mDuration * 1.0f / (VideoTrimmerUtil.MAX_SHOOT_DURATION * 1.0f) * VideoTrimmerUtil.MAX_COUNT_RANGE); //每一小格代表的时长
                rangeWidth = mMaxWidth / VideoTrimmerUtil.MAX_COUNT_RANGE * mThumbsTotalCount;//(SCREEN_WIDTH_FULL - RECYCLER_VIEW_PADDING * 2)/10*15
                mRightProgressPos = VideoTrimmerUtil.MAX_SHOOT_DURATION;//视频最多剪切多长时间，默认10s
            }
        }
//        if (mDuration <= VideoTrimmerUtil.MAX_SHOOT_DURATION) {   //如果视频总时长小于10秒
//            mThumbsTotalCount = VideoTrimmerUtil.MAX_COUNT_RANGE;  //10
//            rangeWidth = mMaxWidth;  //SCREEN_WIDTH_FULL - RECYCLER_VIEW_PADDING * 2;屏幕宽度减两侧padding
//            mRightProgressPos = mDuration;
//        } else {     //如果视频总时长大于10秒               //15秒的视频为例， 15000/10000*10 = 15
//            mThumbsTotalCount = (int) (mDuration * 1.0f / (VideoTrimmerUtil.MAX_SHOOT_DURATION * 1.0f) * VideoTrimmerUtil.MAX_COUNT_RANGE); //每一小格代表的时长
//            rangeWidth = mMaxWidth / VideoTrimmerUtil.MAX_COUNT_RANGE * mThumbsTotalCount;//(SCREEN_WIDTH_FULL - RECYCLER_VIEW_PADDING * 2)/10*15
//            mRightProgressPos = VideoTrimmerUtil.MAX_SHOOT_DURATION;//视频最多剪切多长时间，默认10s
//        }
        mVideoThumbRecyclerView.addItemDecoration(new SpacesItemDecoration2(VideoTrimmerUtil.RECYCLER_VIEW_PADDING, mThumbsTotalCount));//设置recycleview的divider
        mRangeSeekBarView = new RangeSeekBarView(mContext, mLeftProgressPos, mRightProgressPos);
        mRangeSeekBarView.setSelectedMinValue(mLeftProgressPos); //滚动条的取值区间
        mRangeSeekBarView.setSelectedMaxValue(mRightProgressPos);
        mRangeSeekBarView.setStartEndTime(mLeftProgressPos, mRightProgressPos);
        mRangeSeekBarView.setMinShootTime(VideoTrimmerUtil.MIN_SHOOT_DURATION); //最小剪裁时间3秒
        mRangeSeekBarView.setNotifyWhileDragging(true);
        mRangeSeekBarView.setOnRangeSeekBarChangeListener(mOnRangeSeekBarChangeListener);//滚动条加监听
        mSeekBarLayout.addView(mRangeSeekBarView);

        mAverageMsPx = mDuration * 1.0f / rangeWidth * 1.0f; //每毫秒占用的宽度
        averagePxMs = (mMaxWidth * 1.0f / (mRightProgressPos - mLeftProgressPos)); //每PX占用的毫秒数
    }

    private void startShootVideoThumbs(final Context context, final Uri videoUri, int totalThumbsCount, long startPosition, long endPosition) {
        VideoTrimmerUtil.shootVideoThumbInBackground(context, videoUri, totalThumbsCount, startPosition, endPosition,
                new SingleCallback<Bitmap, Integer>() {
                    @Override
                    public void onSingleCallback(final Bitmap bitmap, final Integer interval) {
                        if (bitmap != null) {
                            UiThreadExecutor.runTask("", new Runnable() {
                                @Override
                                public void run() {
                                    mVideoThumbAdapter.addBitmaps(bitmap);
                                }
                            }, 0L);
                        }
                    }
                });
    }

    public void initVideoByURI(final Uri videoURI) {
        mSourceUri = videoURI;
        mVideoView.setVideoURI(videoURI);
        mVideoView.requestFocus();
        mVideoShootTipTv.setText("拖动选择要截取的视频片段");
    }

    private void videoCompleted() {
        Log.i("播放完成", "播放完成===== videoCompleted===");
        seekTo(mLeftProgressPos);
//        setPlayPauseViewIcon(false);
        //视频初始化后直接播放
        mVideoView.start();
        playingRedProgressAnimation();
        setPlayPauseViewIcon(mVideoView.isPlaying());
    }

    private void onVideoReset() {
        mVideoView.pause();
        setPlayPauseViewIcon(false);
    }

    private int isPauseByUser = 0;//0没有1手动暂停

    private void playVideoOrPause() {
        mRedProgressBarPos = mVideoView.getCurrentPosition();
        if (mVideoView.isPlaying()) {
            mVideoView.pause();
            isPauseByUser = 1;
            pauseRedProgressAnimation(); //清除红色指示条动画
        } else {
            mVideoView.start();
            isPauseByUser = 0;
            playingRedProgressAnimation();
        }
        setPlayPauseViewIcon(mVideoView.isPlaying());
    }

    public void setOnTrimVideoListener(VideoTrimListener onTrimVideoListener) {
        mOnTrimVideoListener = onTrimVideoListener;
    }

    private void seekTo(long msec) {
        mVideoView.seekTo((int) msec);
        Log.d(TAG, "seekTo = " + msec);
    }

    private void setPlayPauseViewIcon(boolean isPlaying) {
        mPlayView.setImageResource(isPlaying ? R.drawable.ic_video_pause_black : R.drawable.ic_video_play_black);
    }

    /**
     * 水平滑动了多少px
     */
    private int calcScrollXDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) mVideoThumbRecyclerView.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisibleChildView = layoutManager.findViewByPosition(position);
        int itemWidth = firstVisibleChildView.getWidth();
        return (position) * itemWidth - firstVisibleChildView.getLeft();
    }

    private void playingRedProgressAnimation() {
        Log.i("当前进度", "playingRedProgressAnimation============= = ");
        pauseRedProgressAnimation(); //清除红色指示条动画
        playingAnimation();//重新加载动画
        mAnimationHandler.post(mAnimationRunnable);
    }

    private void playingAnimation() {
        Log.i("开始滚动", "执行playingAnimation方法 >>>>  = ");
        if (mRedProgressIcon.getVisibility() == View.GONE) {
            mRedProgressIcon.setVisibility(View.VISIBLE);
        }
        final LayoutParams params = (LayoutParams) mRedProgressIcon.getLayoutParams();
        int start = (int) (VideoTrimmerUtil.RECYCLER_VIEW_PADDING + (mRedProgressBarPos - scrollPos) * averagePxMs);
//        int start = (int) (VideoTrimmerUtil.RECYCLER_VIEW_PADDING + (mLeftProgressPos - scrollPos) * averagePxMs);//一样的效果
        int end = (int) (VideoTrimmerUtil.RECYCLER_VIEW_PADDING + (mRightProgressPos - scrollPos) * averagePxMs);
        Log.i("开始滚动", "执行playingAnimation方法 >>>> Duration = " + ((mRightProgressPos - scrollPos) - (mRedProgressBarPos - scrollPos)));
        Log.i("开始滚动", "执行playingAnimation方法 >>>> scrollPos = " + scrollPos + ",mRightProgressPos==" + mRightProgressPos + ",mRedProgressBarPos==" + mRedProgressBarPos);
        Log.i("开始滚动", "执行playingAnimation方法 >>>> start = " + start + ",end==" + end);
        mRedProgressAnimator = ValueAnimator.ofInt(start, end).setDuration((mRightProgressPos - scrollPos) - (mRedProgressBarPos - scrollPos));
//        mRedProgressAnimator = ValueAnimator.ofInt(start, end).setDuration((mRightProgressPos - scrollPos) - (mLeftProgressPos - scrollPos));

        mRedProgressAnimator.setInterpolator(new LinearInterpolator());
        mRedProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                params.leftMargin = (int) animation.getAnimatedValue();
                mRedProgressIcon.setLayoutParams(params);
                Log.d(TAG, "----onAnimationUpdate--->>>>>>>" + mRedProgressBarPos);
            }
        });
        mRedProgressAnimator.start();
    }

    private void pauseRedProgressAnimation() { //清除红色指示条动画
        mRedProgressIcon.clearAnimation();
        if (mRedProgressAnimator != null && mRedProgressAnimator.isRunning()) {
            mAnimationHandler.removeCallbacks(mAnimationRunnable);
            mRedProgressAnimator.cancel();
        }
    }

    private Runnable mAnimationRunnable = new Runnable() {
        @Override
        public void run() {  //在动画中实时更新进度条位置
            updateVideoProgress();
        }
    };

    private void updateVideoProgress() {
        long currentPosition = mVideoView.getCurrentPosition();
        if (currentPosition >= (mRightProgressPos)) { //播放到右侧之后，如果当前进度超出了mRightProgressPos，重置视频并重新播放
            mRedProgressBarPos = mLeftProgressPos; //红色进度移回左侧
//            pauseRedProgressAnimation(); //清除红色指示条动画
            seekTo(mRedProgressBarPos);
            playingRedProgressAnimation(); //停止拖动后，开始播放红色指示条动画
//            onVideoPause();  //
        } else {  //正常播放中
            mAnimationHandler.post(mAnimationRunnable);  //实时更新动画
        }
    }

    public void onVideoPause() {    //视频暂停操作
        if (mVideoView.isPlaying()) {
            seekTo(mLeftProgressPos);//复位
            mVideoView.pause(); //暂停播放
            setPlayPauseViewIcon(false); //播放按钮变为播放状态
            mRedProgressIcon.setVisibility(GONE); //红色指示条不显示
        }
    }

    /**
     * Cancel trim thread execut action when finish
     */
    @Override
    public void onDestroy() {
        BackgroundExecutor.cancelAll("", true);
        UiThreadExecutor.cancelAll("");
    }

    private String editMode;
    private String outputName; //保存路径

    public void onSaveClicked(String mode) {
        editMode = mode;
        if (mRightProgressPos - mLeftProgressPos < VideoTrimmerUtil.MIN_SHOOT_DURATION) {
            Toast.makeText(mContext, "视频长不足1秒,无法上传", Toast.LENGTH_SHORT).show();
        } else {
            mVideoView.pause();
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(100);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setTitle("正在处理");

            mProgressDialog.show();

            final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());

//        final String outputName = "trimmedVideo_" + timeStamp + ".mp4";
//        String  outputFile = StorageUtil.getCacheDir() + "/" + outputName;

            String start = VideoTrimmerUtil.convertSecondsToTime(mLeftProgressPos / 1000);
            String duration = VideoTrimmerUtil.convertSecondsToTime((mRightProgressPos - mLeftProgressPos) / 1000);
            //String start = String.valueOf(startMs);
            //String duration = String.valueOf(endMs - startMs);

            /** 裁剪视频ffmpeg指令说明：
             * ffmpeg -ss START -t DURATION -i INPUT -codec copy -avoid_negative_ts 1 OUTPUT
             -ss 开始时间，如： 00:00:20，表示从20秒开始；
             -t 时长，如： 00:00:10，表示截取10秒长的视频；
             -i 输入，后面是空格，紧跟着就是输入视频文件；
             -codec copy -avoid_negative_ts 1 表示所要使用的视频和音频的编码格式，这里指定为copy表示原样拷贝；
             INPUT，输入视频文件；
             OUTPUT，输出视频文件
             */
            //TODO: Here are some instructions
            //https://trac.ffmpeg.org/wiki/Seeking
            //https://superuser.com/questions/138331/using-ffmpeg-to-cut-up-video
            String cmd;
            if (editMode!=null && editMode.equals("extract_bg")){  //提取视频背景音乐
                outputName = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp3";
                cmd  = "ffmpeg " + "-y " + "-ss " + start + " -t " + duration + " -accurate_seek" + " -i " + mSourceUri.getPath() + " -vn " + outputName;

            }else if (editMode!=null && editMode.equals("daofang")){  //视频倒放
                outputName = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp4";
                cmd  = "ffmpeg " + "-y " + "-ss " + start + " -t " + duration + " -accurate_seek" + " -i " + mSourceUri.getPath() + " -vf reverse -af areverse -preset superfast " + outputName;


            }else if (editMode!=null && editMode.equals("gif")){  //GIF导出
                outputName = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".gif";
                cmd  = "ffmpeg " + "-y " + "-ss " + start + " -t " + duration + " -accurate_seek" + " -i " + mSourceUri.getPath() + " -vf scale="+videoWidth+":"+videoHeight+" -f gif -r 10 " + outputName;
            }else{
                outputName = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp4";
                cmd  = "ffmpeg " + "-y " + "-ss " + start + " -t " + duration + " -accurate_seek" + " -i " + mSourceUri.getPath() + " -codec copy -avoid_negative_ts 1 " + outputName;
            }

            //String cmd = "-ss " + start + " -i " + inputFile + " -ss " + start + " -t " + duration + " -vcodec copy " + outputFile;
            //{"ffmpeg", "-ss", "" + startTime, "-y", "-i", inputFile, "-t", "" + induration, "-vcodec", "mpeg4", "-b:v", "2097152", "-b:a", "48000", "-ac", "2", "-ar", "22050", outputFile}
            //String cmd = "-ss " + start + " -y " + "-i " + inputFile + " -t " + duration + " -vcodec " + "mpeg4 " + "-b:v " + "2097152 " + "-b:a " + "48000 " + "-ac " + "2 " + "-ar " + "22050 "+ outputFile;
            String[] command = cmd.split(" ");
            try {
                final String tempOutFile = outputName;
                //FFmpeg修改
                try {
                    RxFFmpegInvoke.getInstance().runCommandRxJava(command).subscribe(new RxFFmpegSubscriber() {
                        @Override
                        public void onFinish() {
                            Log.i("去水印保存", "EpEditor.execCmd onSuccess");
                            mHandler.sendEmptyMessage(MSG_SUCCESS);
                        }

                        @Override
                        public void onProgress(int progress, long progressTime) {
                            Log.i("去水印保存", "EpEditor.execCmd onProgress");
                            Message msg = new Message();
                            Bundle data = new Bundle();
                            data.putFloat("progress", progress);
                            msg.setData(data);
                            msg.what = MSG_PROGRESS;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onCancel() {
                            Log.i("去水印保存", "EpEditor.execCmd onFailure");
                            mHandler.sendEmptyMessage(MSG_CANCLE);
                        }

                        @Override
                        public void onError(String message) {
                            Log.i("去水印保存", "EpEditor.execCmd onFailure");
                            mHandler.sendEmptyMessage(MSG_FAIL);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private ProgressDialog mProgressDialog;
    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    private static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i("视频去水印", "去水印完成，跳转");
                Toast.makeText(mContext, "处理完成", Toast.LENGTH_SHORT).show();
                Intent intent;

                if (editMode != null && editMode.equals("splice_edit")) {  //视频拼接中的视频切割
                    intent = new Intent();
                    intent.putExtra("edit_path", outputName);
                    activity.setResult(Activity.RESULT_OK, intent);
                    activity.finish();

                } else if (editMode != null && editMode.equals("extract_bg")){//提取视频背景音乐
                    MyArt art = new MyArt();
                    art.setHeight(videoHeight);
                    art.setWidth(videoWidth);
                    art.setCreate_time(System.currentTimeMillis() + "");
                    art.setPath(outputName);
                    art.setType(2);
                    art.save();
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
//                    FileUtil.ablumUpdate(mContext, art.getPath(), 2);//更新相册
                    intent = new Intent(activity, ShowMyArtsActivity.class);
                    intent.putExtra(EXTRA_OUTPUT, outputName);
                    intent.putExtra("create_time", art.getTrueCreateTime());
                    intent.putExtra("width", videoWidth);
                    intent.putExtra("height", videoHeight);
                    intent.putExtra("type", "2");
                    activity.startActivity(intent);
                    activity.finish();
                } else if (editMode != null && editMode.equals("gif")){//生成GIF图片
                    MyArt art = new MyArt();
                    art.setHeight(videoHeight);
                    art.setWidth(videoWidth);
                    art.setCreate_time(System.currentTimeMillis() + "");
                    art.setPath(outputName);
                    art.setType(0);
                    art.save();
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
//                    FileUtil.ablumUpdate(mContext, art.getPath(), 2);//更新相册
                    intent = new Intent(activity, ShowMyArtsActivity.class);
                    intent.putExtra(EXTRA_OUTPUT, outputName);
                    intent.putExtra("create_time", art.getTrueCreateTime());
                    intent.putExtra("width", videoWidth);
                    intent.putExtra("height", videoHeight);
                    intent.putExtra("type", "0");
                    activity.startActivity(intent);
                    activity.finish();
                }else {
                    MyArt art = new MyArt();
                    art.setHeight(videoHeight);
                    art.setWidth(videoWidth);
                    art.setCreate_time(System.currentTimeMillis() + "");
                    art.setPath(outputName);
                    art.setType(1);
                    art.save();
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
//                    FileUtil.ablumUpdate(mContext, art.getPath(), 1);//更新相册
                    intent = new Intent(activity, ShowMyArtsActivity.class);
                    intent.putExtra(EXTRA_OUTPUT, outputName);
                    intent.putExtra("create_time", art.getTrueCreateTime());
                    intent.putExtra("width", videoWidth);
                    intent.putExtra("height", videoHeight);
                    intent.putExtra("type", "1");
                    activity.startActivity(intent);
                    activity.finish();
                }

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(mContext, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            } else if (msg.what == MSG_CANCLE) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };

}
